package bugzillapreprocessor.adaptor;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class provides an adaptor for manipulating dates
 * 
 * @author c_haras
 */
public class DateAdaptor {

	/**
	 * This is another version of a method which return the difference in days
	 * between two dates, as strings
	 * 
	 * @param date1
	 *            The later date, as a String
	 * @param date2
	 *            The earlier date, as a String
	 * @return The number of days between both dates
	 */
	static public long getDays(String date1, String date2) {

		date1 = date1.substring(0, 10);
		date2 = date2.substring(0, 10);
		Calendar calendarDate1 = Calendar.getInstance();
		Calendar calendarDate2 = Calendar.getInstance();
		long days = 0;
		try {
			DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
			Date d1 = f.parse(date1);
			Date d2 = f.parse(date2);
			calendarDate1.setTime(d1);
			calendarDate2.setTime(d2);
			while (calendarDate2.before(calendarDate1)) {
				calendarDate2.add(Calendar.DAY_OF_MONTH, 1);
				days++;
			}

		} catch (ParseException ex) {
			//Logger.getLogger(Issue.class.getName()).log(Level.SEVERE, null, ex);
		}
		return days;
	}

	/**
	 * Extracts the year from a date string
	 * 
	 * @param date1
	 *            The date to get the year from
	 * @return The year
	 */
	static public String getYear(String date1) {

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		formatter.setLenient(true);

		Date d = null;
		try {
			d = formatter.parse(date1);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return formatter.format(d);
	}
}
